package dbtest;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.DBManager;

public class DBTestServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req,resp);
	}
	
	private void perform(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		resp.setContentType("text/html;charset=UTF-8");
		req.setCharacterEncoding("UTF-8");
	
		String sql = "select * from UserAccount";
	
		Connection con = null;
		Statement stm = null;
		ResultSet rs = null;
		
		ArrayList<DBTest> list = new ArrayList<DBTest>();
	try{
			
		con = DBManager.getConnection();
		stm = con.createStatement();
		rs = stm.executeQuery(sql);
		while (rs.next()) {
			DBTest test = new DBTest();
			test.setId(rs.getInt("id"));
			test.setName(rs.getString("name"));
			test.setPassword(rs.getString("password"));
			list.add(test);
		}
		rs.close();
	}
	catch (SQLException e) {
		rs = null;
		e.printStackTrace();
	}
	finally {
		if (stm != null) {
			try {stm.close();}
			catch (SQLException e) {e.printStackTrace();}
		}
		if (con != null) {
			try {con.close();}
			catch (SQLException e) {e.printStackTrace();}
		}
	}
	req.setAttribute("list", list);
	RequestDispatcher dispatcher = req.getRequestDispatcher("dbtest.jsp");
	dispatcher.forward(req, resp);//にフォワード
	
	}
}
